package com.hd.crdao.fragment;

import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.hd.crdao.MainActivity;
import com.hd.crdao.R;
import com.hd.crdao.activity.AddressActivity;
import com.hd.crdao.activity.CheckActivity;
import com.hd.crdao.activity.LoanActivity;
import com.hd.crdao.activity.LoginActivity;
import com.hd.crdao.activity.ReleaseActivity;
import com.hd.crdao.activity.SearchActivity;
import com.hd.crdao.adapter.HomeRVAdapter;
import com.hd.crdao.base.BaseFragment;
import com.hd.crdao.bean.AllInfoBean;
import com.hd.crdao.bean.EventBean;
import com.hd.crdao.bean.EventBusBean;
import com.hd.crdao.bean.SearchBean;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.CheckNetworkUtils;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.hss01248.dialog.StyledDialog;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

/**
 *
 *@author Administrator
 *@date 2017/5/10 0010
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener {

    public HomeRVAdapter mHomeRVAdapter;
    public XRecyclerView mXRecyclerView;

    public TextView mEditText;   //搜索框
    TextView mTvLoan;


    TextView mTvSale;
    TextView mTvCheck;
    TextView mTvSell;
    TextView mprice1;

    TextView mprice2;
    TextView mprice3;
    TextView mprice4;
    TextView mprice5;
    RelativeLayout mBieke;

    RelativeLayout mBiaozhi;
    RelativeLayout mBentian;
    RelativeLayout mFute;
    RelativeLayout mFengTian;
    RelativeLayout mDazhong;
    RelativeLayout mBaoma;
    LinearLayout mAll;
    TextView mMore;
    public TextView mSelectcity;
    public List<AllInfoBean.CarInfoListBean> mCarInfoList;
    public LocationClient mLocationClient;
    public BDLocationListener myListener = new MyLocationListener();
    public String mCityName;
    public SmartRefreshLayout mRefreshLayout;
    public Handler mHandler = new Handler();


    @Override

    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mRefreshLayout = (SmartRefreshLayout) mViewRoot.findViewById(R.id.refreshLayout);
        mXRecyclerView = (XRecyclerView) mViewRoot.findViewById(R.id.recyclerview);
        //    mMyListView.setDividerHeight(0);
        GridLayoutManager layoutManager = new GridLayoutManager(UIUtils.getContext(), 2, LinearLayoutManager.VERTICAL, false);
        mXRecyclerView.setLayoutManager(layoutManager);
        View view = getHeadView();
        mXRecyclerView.addHeaderView(view);

        mHomeRVAdapter = new HomeRVAdapter(mCarInfoList, getContext());
        mXRecyclerView.setAdapter(mHomeRVAdapter);

        mXRecyclerView.setPullRefreshEnabled(true);
        mXRecyclerView.setLoadingMoreEnabled(false);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.autoLoadmore();

        initBaiduLocation();

    }

    @NonNull
    private View getHeadView() {
        View view = View.inflate(UIUtils.getContext(), R.layout.home_head, null);
        mEditText = (TextView) view.findViewById(R.id.search);
        mSelectcity = (TextView) view.findViewById(R.id.home_selectcity);
        mTvLoan = (TextView) view.findViewById(R.id.tv_loan);
        mTvSale = (TextView) view.findViewById(R.id.tv_sale);
        mTvCheck = (TextView) view.findViewById(R.id.tv_check);
        mTvSell = (TextView) view.findViewById(R.id.tv_sell);
        mprice1 = (TextView) view.findViewById(R.id.price1);
        mprice2 = (TextView) view.findViewById(R.id.price2);
        mprice3 = (TextView) view.findViewById(R.id.price3);
        mprice4 = (TextView) view.findViewById(R.id.price4);
        mprice5 = (TextView) view.findViewById(R.id.price5);
        mBieke = (RelativeLayout) view.findViewById(R.id.bieke);
        mBiaozhi = (RelativeLayout) view.findViewById(R.id.biaozhi);
        mBentian = (RelativeLayout) view.findViewById(R.id.bentian);
        mFute = (RelativeLayout) view.findViewById(R.id.fute);
        mFengTian = (RelativeLayout) view.findViewById(R.id.fengtian);
        mDazhong = (RelativeLayout) view.findViewById(R.id.dazhong);
        mBaoma = (RelativeLayout) view.findViewById(R.id.baoma);
        mMore = (TextView) view.findViewById(R.id.more);
        mAll = (LinearLayout) view.findViewById(R.id.all);
        return view;
    }

    private void initBaiduLocation() {
        mLocationClient = new LocationClient(UIUtils.getContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        initLocation();
        if (CheckNetworkUtils.isNetworkAvailable()) {
            mLocationClient.start();
        } else {
//            mSelectcity.setText("手动定位");
        }
    }

    /**
     * 定位设置一些参数信息
     */
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span = 1000;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps
        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }


    @Override
    protected void initListener() {

        mEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(UIUtils.getContext(), SearchActivity.class));
            }
        });

        mTvLoan.setOnClickListener(this);
        mTvSale.setOnClickListener(this);
        mTvCheck.setOnClickListener(this);
        mTvSell.setOnClickListener(this);
        mSelectcity.setOnClickListener(this);

        mprice1.setOnClickListener(this);
        mprice2.setOnClickListener(this);
        mprice3.setOnClickListener(this);
        mprice4.setOnClickListener(this);
        mprice5.setOnClickListener(this);

        mBieke.setOnClickListener(this);
        mBiaozhi.setOnClickListener(this);
        mBentian.setOnClickListener(this);
        mFute.setOnClickListener(this);
        mFengTian.setOnClickListener(this);
        mDazhong.setOnClickListener(this);
        mBaoma.setOnClickListener(this);
        mMore.setOnClickListener(this);
        mAll.setOnClickListener(this);

        mRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                mRefreshLayout.finishLoadmore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mHandler.postDelayed(new LoadRunnale(), 1500);
                ALog.d("走的是布局刷新的方法");
            }
        });

    }


    @Override
    protected void initData() {
    }

    /**
     * 加载数据
     */
    private void loadData(final String cityName) {
        HashMap<String, String> map = new HashMap<>();
        map.put("appFlag", "true");
        if (cityName != null) {
            map.put("cityName", cityName);
        } else {
            map.put("cityName", "");
        }
        try {
            OkHttpUtils.post().url(Constants.HOME_INFORMATION_URL)
                    .params(map)
                    .build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    ALog.d("网络开了个小差");
                    mHandler.postDelayed(new OnErrorRunnable(), 3000);
                }

                @Override
                public void onResponse(final String response, int id) {
                    ALog.d(response);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mCarInfoList = new Gson().fromJson(response, AllInfoBean.class).getCarInfoList();
                            mHomeRVAdapter = new HomeRVAdapter(mCarInfoList, getContext());
                            mXRecyclerView.setAdapter(mHomeRVAdapter);
                            mHomeRVAdapter.notifyDataSetChanged();
                        }
                    }, 1500);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    //    相应点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_loan://融资贷款

                startActivity(new Intent(UIUtils.getContext(), LoanActivity.class));
                break;
            case R.id.tv_sale:  //新车分销
                EventBus.getDefault().postSticky(new EventBusBean(false));
                ChangeFindFrangment();
                break;
            case R.id.tv_check:     //车辆检测
                startActivity(new Intent(UIUtils.getContext(), CheckActivity.class));
                break;
            case R.id.tv_sell:
                if (SPUtils.getBoolean("hasLogin", false)) {
                    startActivity(new Intent(UIUtils.getContext(), ReleaseActivity.class));
                } else {
                    startActivity(new Intent(UIUtils.getContext(), LoginActivity.class));
                }
                break;
            case R.id.home_selectcity:
                selectCity();
                // startActivity(new Intent(UIUtils.getContext(),TestActivity.class));
                break;
            case R.id.price1:
                EventBus.getDefault().postSticky(new SearchBean("10万以下"));
                ChangeFindFrangment();
                break;
            case R.id.price2:
                EventBus.getDefault().postSticky(new SearchBean("10-15万"));
                ChangeFindFrangment();
                break;
            case R.id.price3:
                EventBus.getDefault().postSticky(new SearchBean("15-20万"));
                ChangeFindFrangment();
                break;
            case R.id.price4:
                EventBus.getDefault().postSticky(new SearchBean("20-30万"));
                ChangeFindFrangment();
                break;
            case R.id.price5:
                EventBus.getDefault().postSticky(new SearchBean("30万以上"));
                ChangeFindFrangment();
                break;
            case R.id.bieke:
//                MyToast.show("别克");
                EventBus.getDefault().postSticky(new SearchBean("别克"));
                ChangeFindFrangment();
                break;
            case R.id.biaozhi:
//                MyToast.show("标致");
                EventBus.getDefault().postSticky(new SearchBean("标致"));
                ChangeFindFrangment();
                break;
            case R.id.bentian:
//                MyToast.show("本田");
                EventBus.getDefault().postSticky(new SearchBean("本田"));
                ChangeFindFrangment();
                break;
            case R.id.fute:
//                MyToast.show("福特");
                EventBus.getDefault().postSticky(new SearchBean("福特"));
                ChangeFindFrangment();
                break;
            case R.id.fengtian:
//                MyToast.show("丰田");
                EventBus.getDefault().postSticky(new SearchBean("丰田"));
                ChangeFindFrangment();
                break;
            case R.id.dazhong:
//                MyToast.show("大众");
                EventBus.getDefault().postSticky(new SearchBean("大众"));
                ChangeFindFrangment();
                break;
            case R.id.baoma:
//                MyToast.show("宝马");
                EventBus.getDefault().postSticky(new SearchBean("宝马"));
                ChangeFindFrangment();
                break;
            case R.id.more:
//                MyToast.show("更多");
                EventBus.getDefault().postSticky(new EventBusBean(true));
                ChangeFindFrangment();
                break;
            case R.id.all:
//                MyToast.show("全部");
                EventBus.getDefault().postSticky(new EventBusBean(true));
                ChangeFindFrangment();
                break;


        }
    }

    /**
     * 切换到第二个找车的fragemnt
     */
    private void ChangeFindFrangment() {
        MainActivity activity = (MainActivity) getActivity();
        activity.setIndexSelected(1);
        activity.mRadioGroup.check(R.id.rb_find);
    }

    /**
     * 选择城市
     */
    private void selectCity() {
//        startActivityForResult(new Intent(UIUtils.getContext(), AddressActivity.class), GET_ADDRESS);
        Intent intent = new Intent(UIUtils.getContext(), AddressActivity.class);
        intent.putExtra("fromWhere", "home");
        startActivity(intent);
    }


    private class LoadRunnale implements Runnable {
        @Override
        public void run() {
//            加载数据
            loadData(mCityName);
            mHomeRVAdapter.notifyDataSetChanged();
            mRefreshLayout.finishRefresh();
            StyledDialog.dismissLoading();
        }
    }

    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (!TextUtils.isEmpty(location.getCity())) {
                String locationCity = location.getCity();
                mCityName = locationCity;
                loadData(mCityName);
                SPUtils.saveString("home_cityName", locationCity);
                mSelectcity.setText(locationCity);

            } else {
//                mSelectcity.setText("定位失败");
                mCityName = "";
                loadData("");
            }

            mLocationClient.stop();
            mLocationClient.unRegisterLocationListener(myListener);

        }

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mLocationClient.stop();
        mLocationClient.unRegisterLocationListener(myListener);

    }

    /**
     * 加载数据失败时的一个延时任务   隐藏掉progressbar
     */
    private class OnErrorRunnable implements Runnable {
        @Override
        public void run() {
            StyledDialog.dismissLoading();
            MyToast.show("连接超时...");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getCityName(EventBean eventBean) {
        mCityName = eventBean.getCityName();
        SPUtils.saveString("home_cityName", mCityName);  //把选择的城市存起来,搜索店铺页面需要
        mSelectcity.setText(mCityName);
        loadData(mCityName);
    }
}
